//
//  DoorListViewController.m
//  RONGAO
//
//  Created by wei wang on 2017/2/22.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "DoorListViewController.h"
#import "MJRefresh.h"
#import "AppDelegate.h"
#import "DoorListCell.h"
#import "DoorAddViewController.h"
#import "DoorHomeViewController.h"


@interface DoorListViewController ()<UITableViewDelegate,UITableViewDataSource,MyCameraDelegate>
{
    
    BOOL isRunOneTime;
    NSMutableArray *arrReConntFlag;
    BOOL isRecvSetArmResp;
    
    
}
/** testbluetoothArray **/
@property(nonatomic,strong) NSMutableArray *array;

/** UItableView **/
@property(nonatomic,strong) UITableView *tableView;

/** 摄像头数组 **/
@property(nonatomic,strong) NSMutableArray *searchedData;

@end

@implementation DoorListViewController

- (NSMutableArray *)searchedData{
    
    if (!_searchedData) {
        
        _searchedData = [NSMutableArray array];
    }
    return _searchedData;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    [self setNavigationStyle];
    
    [self masLayoutSubview];

    [self.tableView.mj_header beginRefreshing];
    
    __weak typeof(self) weakself = self;

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [weakself.tableView.mj_header endRefreshing];
        
    });

    
    [[AppDelegate globalDelegate] loadDeviceFromDatabase];

    [self.searchedData addObjectsFromArray:[[AppDelegate globalDelegate] loadDeviceFromDatabase:[NSString stringWithFormat:@"%d",0]]];
    [self.searchedData addObjectsFromArray:[[AppDelegate globalDelegate] loadDeviceFromDatabase:[NSString stringWithFormat:@"%d",1]]];
    [self setCamera];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    
    __weak typeof(self) weakself = self;
    
    self.tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        
        [[DTCloudManager defaultJNI_iOS_SDK] getAllDeviceSuccessCallback:^(NSArray *deviceList) {
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:4];
            for (DTDevice *device in deviceList)
            {
                if ([device.deviceTypeID isEqualToString:TYPEID])
                {
                    [array addObject:device];
                }
            }
            weakself.array = array;
            [weakself.tableView reloadData];

        } errorCallback:^(NSDictionary *dic) {
            
            NSLog(@"%@",dic);
            
        }];
        
        
    }];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(DeviceisOnline:) name:@"Deviceisonline" object:nil];
    arrReConntFlag = [[NSMutableArray alloc] init];
    
    isRunOneTime = NO;
}

- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
#if defined(P2PNETCAM_HAIER)
    // disconnect device
    [self disLoopConnect];
#else
    //self.navigationController.navigationBar.translucent = NO;
#endif
    for( NSMutableArray* store in arrReConntFlag ) {
        if( [store count] == 3 ) {
            NSTimer* timer = [store objectAtIndex:2];
            [timer invalidate];
            //[timer release];
        }
    }
    [arrReConntFlag removeAllObjects];

    
}



- (void)DeviceisOnline:(NSNotification *)notifine{
    
    DTDevice *info = notifine.object;
    
    for (DTDevice *obc in self.array) {
        
        if ([info.macAddress isEqualToString:obc.macAddress]) {
            
            obc.macAddress = info.macAddress;
            obc.isOnline = info.isOnline;
            
        }
        
    }
    
    [self.tableView reloadData];
}

- (void)onRightButtonClick:(id)sender{

    DoorAddViewController *vc = [[DoorAddViewController alloc] init];
    vc.doorType = TranslationDoor;
    [self.navigationController pushViewController:vc animated:YES];
    
}


- (void)setNavigationStyle{
    
    [self setRightButtonImage:[UIImage imageNamed:@"icon_add_nor"]];
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setNavigationTitle:@"设备列表" titleColor:nil];
    
}


- (void)setCamera{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"P2PPushUpdateDelegateNotification" object:self userInfo:nil];
    for (MyCamera *camera in self.searchedData)
    {
        camera.delegate2 = self;
        NSLog(@"camera.uid:%@", camera.uid);
        
        NSString *device_uid = camera.uid;
        if (nil == device_uid || [device_uid isEqualToString:@""]) {
            device_uid = camera.deviceID;
        }
        
        for (MyCamera *camera in self.searchedData)
            
            
        {
            camera.delegate2 = self;
            NSLog(@"camera.uid:%@", camera.uid);
            
            NSString *device_uid = camera.uid;
            if (nil == device_uid || [device_uid isEqualToString:@""]) {
                device_uid = camera.deviceID;
            }
            
            if (device_uid)
            {
                [arrReConntFlag addObject:[NSMutableArray arrayWithObjects:[NSString stringWithString:device_uid], [NSNumber numberWithInt:0], nil]];
            }
        }
        
#if defined(P2PMENBOSHI) || defined(P2PBANDIANGOU) || defined(P2PXBROBOT) || defined(P2PWEXVS) //|| defined(P2PAUROCAM_WEX)
        [self armingSMsgAVIoctrlGet:camera];
#endif
#if defined(P2PMONITOR_LAMP) || defined(P2PVIDEODB)
        [self ledSMsgAVIoctrlGet:camera];
#endif
        
#if defined(P2PBANDIANGOU) || defined(P2PWEXVS)
        [self externalDeviceListSMsgAVIoctrlGet:camera];
        
        camera.isShowListView = NO;
#endif
    }
    [self restoreModeIndexToAllCam];

}

- (void)restoreModeIndexToAllCam {
    
    for (int i=0; i<self.searchedData.count; i++) {
        MyCamera *cam = (MyCamera *)[self.searchedData objectAtIndex:i];
        
        [self restoreModeIndexToCam:cam];
    }
}

- (void)restoreModeIndexToCam:(MyCamera *)cam {
    
    cam.newModeValue1 = cam.orgModeValue1;
    
}



#if defined(P2PMONITOR_LAMP) || defined(P2PVIDEODB)
- (void)ledSMsgAVIoctrlGet:(MyCamera *)camera
{
    NSLog(@"armingSMsgAVIoctrlGet");
    SMsgAVIoctrlThirdpartReq *structArming = (SMsgAVIoctrlThirdpartReq *)malloc(sizeof(SMsgAVIoctrlThirdpartReq));
    memset(structArming, 0, sizeof(SMsgAVIoctrlThirdpartReq));
    
    structArming->command_types_ = THIRD_PART_GET_LED_STATUS;
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_THIRDPART_SETTING_REQ
                           Data:(char *)structArming
                       DataSize:sizeof(SMsgAVIoctrlThirdpartReq)];
    free(structArming);
}

- (void)ledSMsgAVIoctrlSet:(MyCamera *)camera
{
    SMsgAVIoctrlThirdpartReq *s = (SMsgAVIoctrlThirdpartReq *)malloc(sizeof(SMsgAVIoctrlThirdpartReq));
    memset(s, 0, sizeof(SMsgAVIoctrlThirdpartReq));
    
    s->command_types_ = THIRD_PART_SET_LED_STATUS;
    s->value1_ = (int)camera.newContrlValue1;
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_THIRDPART_SETTING_REQ
                           Data:(char *)s
                       DataSize:sizeof(SMsgAVIoctrlThirdpartReq)];
    
    free(s);
    
}
#endif




#if defined(P2PMENBOSHI) || defined(P2PBANDIANGOU) || defined(P2PXBROBOT) || defined(P2PWEXVS) || defined(P2PVIDEODB) || defined(P2PAUROCAM_WEX)
#pragma mark - get set arming or disarming
- (void)armingSMsgAVIoctrlGet:(MyCamera *)camera
{
    NSLog(@"armingSMsgAVIoctrlGet");
    SMsgAVIoctrlThirdpartReq *structArming = (SMsgAVIoctrlThirdpartReq *)malloc(sizeof(SMsgAVIoctrlThirdpartReq));
    memset(structArming, 0, sizeof(SMsgAVIoctrlThirdpartReq));
    
    structArming->command_types_ = THIRD_PART_GET_ALARMED_STATUS;
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_THIRDPART_SETTING_REQ
                           Data:(char *)structArming
                       DataSize:sizeof(SMsgAVIoctrlThirdpartReq)];
    free(structArming);
}

#endif

- (void)externalDeviceListSMsgAVIoctrlGet:(MyCamera *)camera
{
    NSLog(@"externalDeviceListSMsgAVIoctrlGet");
    SmsgAVIoctrlEditAllDevicesReq *s = (SmsgAVIoctrlEditAllDevicesReq *)malloc(sizeof(SmsgAVIoctrlEditAllDevicesReq));
    memset(s, 0, sizeof(SmsgAVIoctrlEditAllDevicesReq));
    
    s->type = EDIT_433_LIST_TYPE_GET_ALARM_INFO ;
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_433_EDITDIVICES_LIST_REQ
                           Data:(char *)s
                       DataSize:sizeof(SmsgAVIoctrlEditAllDevicesReq)];
    free(s);
}


/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager]
             URLsForDirectory:NSDocumentDirectory
             inDomains:NSUserDomainMask] lastObject];
}

- (NSString *) pathForDocumentsResource:(NSString *) relativePath {
    
    static NSString* documentsPath = nil;
    
    if (nil == documentsPath) {
        
        NSArray* dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentsPath = [dirs objectAtIndex:0];
    }
    
    return [documentsPath stringByAppendingPathComponent:relativePath];
}


#pragma mark - MyCameraDelegate Methods
- (void)camera:(MyCamera *)camera _didChangeSessionStatus:(NSInteger)status
{
    if (camera.sessionState == CONNECTION_STATE_TIMEOUT) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            
            [camera disconnect];
            
        });
    }
    
    NSString *device_uid = camera.uid;
    
    if (nil == device_uid || [device_uid isEqualToString:@""]) {
        device_uid = camera.deviceID;
    }
    
    if( camera.sessionState == CONNECTION_STATE_DISCONNECTED ||
       camera.sessionState == CONNECTION_STATE_UNKNOWN_DEVICE ||
       camera.sessionState == CONNECTION_STATE_TIMEOUT ||
       camera.sessionState == CONNECTION_STATE_UNSUPPORTED ||
       camera.sessionState == CONNECTION_STATE_CONNECT_FAILED ) {
        
        NSMutableArray* storeToSetTimer = nil;
        int nReConntFlag = -1;
        for( NSMutableArray* store in arrReConntFlag ) {
            
            
            NSString* uidInStore = [store objectAtIndex:0];
            if( NSOrderedSame == [device_uid compare:uidInStore options:NSCaseInsensitiveSearch] ) {
                NSNumber* num = [store objectAtIndex:1];
                nReConntFlag = [num intValue];
                [store replaceObjectAtIndex:1 withObject:[NSNumber numberWithInt:++nReConntFlag]];
                storeToSetTimer = store;
                break;
            }
        }
        if( nReConntFlag == 1 ) {
            NSLog( @"Camera UID:%@ will re-connect in 30sec...", device_uid );
            [storeToSetTimer addObject:[NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(ReConnectAfter30Sec:) userInfo:[NSArray arrayWithObjects:[NSString stringWithString:device_uid], [NSValue valueWithPointer:(__bridge const void * _Nullable)(camera)], nil] repeats:NO] ];
        }
        else {
            NSLog( @"Camera UID:%@ give up re-connect nReConntFlag:%d", device_uid, nReConntFlag );
        }
    }
    else if( camera.sessionState == CONNECTION_STATE_CONNECTED ) {
        for( NSMutableArray* store in arrReConntFlag ) {
            NSString* uidInStore = [store objectAtIndex:0];
            if( NSOrderedSame == [device_uid compare:uidInStore options:NSCaseInsensitiveSearch] ) {
                [store replaceObjectAtIndex:1 withObject:[NSNumber numberWithInt:0]];
                NSLog( @"Camera UID:%@ reset re-connect flag as -0-", device_uid );
                break;
            }
        }
        
        
    }
    
    
    
}

- (void)ReConnectAfter30Sec:(NSTimer*)theTimer
{
    
    NSArray* arrParam = (NSArray*)theTimer.userInfo;
    NSString* strUid = [arrParam objectAtIndex:0];
    MyCamera* camera = (MyCamera*)[(NSValue*)[arrParam objectAtIndex:1] pointerValue];
    
    BOOL isGo = NO;
#if defined(P2PWEXVS)
    
    if ([camera.deviceType isEqualToString:DEV_TYPE_ADD_3_SAFEBOX]) {
        
        
        isGo = NO;
    } else {
        isGo = YES;
    }
#else
    isGo = YES;
    
#endif
    
    if (isGo) {
        
        
        BOOL bIsValid_Camera = FALSE;
        for( NSMutableArray* store in arrReConntFlag ) {
            NSString* uidInStore = [store objectAtIndex:0];
            if( NSOrderedSame == [strUid compare:uidInStore options:NSCaseInsensitiveSearch] ) {
                bIsValid_Camera = TRUE;
                if( [store count] == 3 ) {
                    NSTimer* timer = [store objectAtIndex:2];
                    [timer invalidate];
                    //				[timer release];
                    [store removeObjectAtIndex:2];
                    break;
                }
            }
        }
        if( bIsValid_Camera ) {
            NSLog( @"ReConnectAfter30Sec camera.uid:%@ camera connect and start!", camera.uid );
            
            [camera connect:camera.uid];
            [camera start:0];
        }
        else {
            NSLog( @"ReConnectAfter30Sec with deallocated instance!!! camera.uid:%@", camera.uid );
        }
        
    }
}



- (void)camera:(MyCamera *)camera _didChangeChannelStatus:(NSInteger)channel ChannelStatus:(NSInteger)status
{
    if (status == CONNECTION_STATE_TIMEOUT) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            
            [camera stop:channel];
            
            usleep(500 * 1000);
            
            [camera disconnect];
        });
    }

}


- (void)camera:(MyCamera *)camera_ _didReceiveIOCtrlWithType:(NSInteger)type Data:(const char *)data DataSize:(NSInteger)size {
    
    NSLog(@"CLFVC _didReceiveIOCtrlWithType type:%ld(%lx)", (long)type, (long)type);
    
#if defined(DEV_LIST_CONTRL)|| defined(P2PVIDEODB)
    if (type == IOTYPE_USER_IPCAM_THIRDPART_SETTING_RESP) {
        SMsgAVIoctrlThirdpartResp *s = (SMsgAVIoctrlThirdpartResp*)data;
        NSLog(@"IOTYPE_USER_IPCAM_THIRDPART_SETTING_RESP s->command_types_:%d, s->result_:%d, s->value_:%d",
              s->command_types_, s->result_, s->value_);
        if (THIRD_PART_GET_LED_STATUS == s->command_types_) {
            //[[iToast makeText:NSLocalizedString(@"IR Correct Success", @"")]show];
            
#if defined(P2PVIDEODB)
            
            
            if (s->result_ < 0) {
            } else {
                camera_.orgContrlValue1 = s->value_;
                camera_.newContrlValue1 = s->value_;
                
            }
#else
            camera_.orgContrlValue1 = s->result_;
            camera_.newContrlValue1 = s->result_;
            
#endif
            
            
#if 0
            if (0 == s->result_) {
                NSLog(@"camera_.orgContrlValue1:%ld, camera_.newContrlValue1:%ld",
                      (long)camera_.orgContrlValue1, (long)camera_.newContrlValue1);
                //if (camera_.orgArming < 0)
                {
                    camera_.orgContrlValue1 = s->value_;
                    camera_.newContrlValue1 = s->value_;
                    
                    
                }
            } else {
                /*
                 dispatch_queue_t queue = dispatch_queue_create("led_get_status", NULL);
                 dispatch_async(queue, ^{
                 
                 usleep(3*1000*1000);
                 
                 [self ledSMsgAVIoctrlGet:camera_];
                 });
                 
                 dispatch_release(queue);
                 */
            }
#endif
            
        } else if (THIRD_PART_SET_LED_STATUS == s->command_types_) {
            //[[iToast makeText:NSLocalizedString(@"IR Correct Fail", @"")]show];
            NSLog(@"camera_.newContrlValue1:%ld", (long)camera_.newContrlValue1);
            if (0 == s->result_) {
                camera_.orgContrlValue1 = camera_.newContrlValue1;
                
                
            } else {
                
                camera_.orgContrlValue1 = (camera_.newContrlValue1 == 1) ? 0 : 1;
                
            }
            
        }
    }
    
#endif
    
#if defined(P2PMENBOSHI) || defined(P2PBANDIANGOU) || defined(P2PXBROBOT) || defined(P2PWEXVS)  || defined(P2PAUROCAM_WEX) //|| defined(P2PVIDEODB)
    if (type == IOTYPE_USER_IPCAM_THIRDPART_SETTING_RESP) {
        SMsgAVIoctrlThirdpartResp *s = (SMsgAVIoctrlThirdpartResp*)data;
        NSLog(@"IOTYPE_USER_IPCAM_THIRDPART_SETTING_RESP s->command_types_:%d, s->result_:%d, s->value_:%d",
              s->command_types_, s->result_, s->value_);
        if (THIRD_PART_GET_ALARMED_STATUS == s->command_types_) {
            //[[iToast makeText:NSLocalizedString(@"IR Correct Success", @"")]show];
            
            if (0 == s->result_) {
                NSLog(@"camera_.orgArming:%ld, camera_.newArming:%ld",
                      (long)camera_.orgArming, (long)camera_.newArming);
                //if (camera_.orgArming < 0)
                {
                    camera_.orgArming = s->value_;
                    camera_.newArming = s->value_;
                    
                    [self.tableView reloadData];
                    
                }
            } else {
            }
            
            
        } else if (THIRD_PART_SET_ALARMED_STATUS == s->command_types_) {
            //[[iToast makeText:NSLocalizedString(@"IR Correct Fail", @"")]show];
            
            if (0 == s->result_) {
                camera_.orgArming = s->value_;
                NSString *arm;
                if (camera_.orgArming) {
                    arm = NSLocalizedString(@"Arming", @"");
                } else {
                    arm = NSLocalizedString(@"Disarming", @"");
                }
                NSString *showStr = [NSString stringWithFormat:@"%@  %@", camera_.name, arm];
                
                //                [[iToast makeText:showStr]show];
                
                [self.tableView reloadData];
                
            } else {
                NSString *arm;
                if (camera_.newArming) {
                    arm = NSLocalizedString(@"Arming", @"");
                } else {
                    arm = NSLocalizedString(@"Disarming", @"");
                }
                NSString *showStr = [NSString stringWithFormat:@"%@  %@ Fail", camera_.name, arm];
                
                //                [[iToast makeText:showStr]show];
                
                
            }
            
        }
    }
    
#endif
    
    if (type == IOTYPE_USER_IPCAM_EVENT_REPORT) {
        NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT camera_.uid:%@", camera_.uid);
        
        SMsgAVIoctrlEvent *s = (SMsgAVIoctrlEvent *)data;
        
        NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT s->event:%d", s->event);
        NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT s->time:%d", s->time);
        
        NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT s->stTime.hour:%d", s->stTime.hour);
        NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT s->stTime.minute:%d", s->stTime.minute);
        NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT s->stTime.second:%d", s->stTime.second);
        
        
        
    } else if(type == IOTYPE_USER_IPCAM_433_EDITDIVICES_LIST_RESP) {
        SmsgAVIoctrlEditAllDevicesResp *s = (SmsgAVIoctrlEditAllDevicesResp*)data;
        NSLog(@"CameraListForLiveViewController IOTYPE_USER_IPCAM_433_EDITDIVICES_LIST_RESP s->result_:%d, s->type:%d, s->alarm_type:%d, s->devices_.num_:%d", s->result, s->type, s->alarm_type, s->devices_.num_);
        
        isRecvSetArmResp = YES;
        
        if (0 == s->result) {
            
            NSLog(@"begin camera_.orgModeValue1:%ld, camera_.newModeValue1:%ld", (long)camera_.orgModeValue1, (long)camera_.newModeValue1);
            camera_.orgModeValue1 = camera_.newModeValue1;
            
            if (EDIT_433_LIST_TYPE_GET_ALARM_INFO == s->type) {
            } else if (EDIT_433_LIST_TYPE_SET_ALARM_TYPE == s->type) {
            } else if (EDIT_433_LIST_TYPE_SET_CLOSE_TYPE == s->type) {
            } else if (EDIT_433_LIST_TYPE_SAVE_USER_DEFINED_TYPE == s->type) {
            }
        }
        
    }
    
}

- (void)externalDeviceListSMsgAVIoctrlSet:(MyCamera *)camera ctrlType:(NSInteger)type armType:(NSInteger)arm_type
{
    NSLog(@"externalDeviceListSMsgAVIoctrlSet");
    
    isRecvSetArmResp = NO;
    
    SmsgAVIoctrlEditAllDevicesReq *s = (SmsgAVIoctrlEditAllDevicesReq *)malloc(sizeof(SmsgAVIoctrlEditAllDevicesReq));
    memset(s, 0, sizeof(SmsgAVIoctrlEditAllDevicesReq));
    
    s->type = (int)type;
    
    s->alarm_type = (int)arm_type;
    
    ////int     alarm_type;//0-disable, 1-onekey-alarm , 2-home-alarm, 3-store-alarm, 4-use-defined, 5-invalid
    
    switch (s->alarm_type) {
        case BDG_MODE_DEFAULT_INDEX:
            break;
            
        case BDG_MODE_ONEKEY_INDEX:
            break;
            
        case BDG_MODE_HOME_INDEX:
            break;
            
        case BDG_MODE_STORE_INDEX:
            break;
            
        case BDG_MODE_USER_INDEX:
        {
            
        }
            break;
            
        case BDG_MODE_DEVICE_INDEX:
        {
            
        }
            break;
            
        default:
        {
        }
            break;
            
    }
    
    NSInteger num = camera.externalDeviceListArr.count;
    NSLog(@"num=%ld", (long)num);
    
    s->devices_.num_ = (int)num;
    
    for (int i=0; i<camera.externalDeviceListArr.count; i++) {
        
        /*
         Alarm433Device *dev = (Alarm433Device *)[camera.externalDeviceListArr objectAtIndex:i];
         //dev.key = [NSString stringWithUTF8String:s->devices_.devices_array_[i].key_];
         memcpy(s->devices_.devices_array_[i].key_, dev.key.UTF8String, sizeof(s->devices_.devices_array_[i].key_));
         
         //dev.alias = [NSString stringWithUTF8String:s->devices_.devices_array_[i].aliase_];
         memcpy(s->devices_.devices_array_[i].aliase_, dev.alias.UTF8String, sizeof(s->devices_.devices_array_[i].aliase_));
         
         s->devices_.devices_array_[i].device_type_ = dev.device_type;
         s->devices_.devices_array_[i].device_vender_ = dev.device_vender;
         
         #if defined(BUILD_FOR_GANSU_CAM)
         s->devices_.devices_array_[i].device_alarmed = dev.new_device_alarmed;
         s->devices_.devices_array_[i].alarm_ptz_preset = dev.new_alarm_ptz_preset;
         s->devices_.devices_array_[i].device_closed = dev.new_device_closed;
         #endif
         
         dev.device_alarmed = dev.new_device_alarmed;
         dev.alarm_ptz_preset = dev.new_alarm_ptz_preset;
         dev.device_closed = dev.new_device_closed;
         
         NSLog(@"i:%d dev.alias:%@, dev.key:%@", i, dev.alias, dev.key);
         NSLog(@"dev.device_type:%ld, dev.device_vender:%ld, dev.device_alarmed:%ld, dev.alarm_ptz_preset:%ld, dev.device_closed:%ld", (long)dev.device_type, (long)dev.device_vender, (long)dev.device_alarmed, (long)dev.alarm_ptz_preset, (long)dev.device_closed);
         */
    }
    
    
    NSLog(@"externalDeviceListSMsgAVIoctrlSet IOTYPE_USER_IPCAM_433_EDITDIVICES_LIST_REQ s->type:%d, s->alarm_type:%d, s->devices_.num_:%d", s->type, s->alarm_type, s->devices_.num_);
    
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_433_EDITDIVICES_LIST_REQ
                           Data:(char *)s
                       DataSize:sizeof(SmsgAVIoctrlEditAllDevicesReq)];
    free(s);
}



- (void)externalDeviceListSetTask {
    
    for (int i=0; i<100; i++) {
        if (isRecvSetArmResp) {
            break;
        }
        NSLog(@"externalDeviceListSetTask i=%d", i);
        usleep(100*1000);
    }
    
}




#pragma mark - --------------------------UITableView dataSource--------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.array.count;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 56;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}

#pragma mark - --------------------------UITableView delegate--------------------------

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DoorListCell *cell = [DoorListCell dequeueReusableWithTableView:tableView];
    
    DTDevice *info = self.array[indexPath.row];
    
    cell.deviceNameLabel.text = info.deviceName;
    if (info.isOnline == YES) {
        
        cell.stautsBtn.selected = YES;
        
    }else{
        
        cell.stautsBtn.selected = NO;

    }
    
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    DTDevice *info = self.array[indexPath.row];
    
   
    if (info.isOnline == YES){
        [AppDelegate globalDelegate].doorWiFiModel = info;
        /* 选择平移门时首先查询运行模式*/
        
        [[AppDelegate globalDelegate] sendCommandByFunctionCode:@"1001" functionCommand:@"0301"];
        
        for (MyCamera *camerainfo in self.searchedData) {
            
            
            if ([camerainfo.uid isEqualToString:EXRACT_OBJECT([AppDelegate globalDelegate].doorWiFiModel.macAddress])){
                
                [self getIsRecvAudioFormat:camerainfo];
                
            }
                 
                 }
                 
            DoorHomeViewController *vc = [[DoorHomeViewController alloc] init];
                 
                 
            [self.navigationController pushViewController:vc animated:YES];
            
            }else{
                     
            return [SVProgressHUD showErrorWithStatus:@"设备离线"];
    }

   
   
}


- (BOOL)getIsRecvAudioFormat:(MyCamera *)cam {
    BOOL isRecvAudioFormat = NO;
    
#if defined(AUDIO_TO_SUPPORT)
    if (cam) {
        if (cam.sessionState == CONNECTION_STATE_CONNECTED) {
            
            //if ([camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED)
            
            isRecvAudioFormat = cam.isRecvAudioFormat;
            
            if (isRecvAudioFormat) {
                
            } else {
                NSLog(@"IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ");
                SMsgAVIoctrlGetAudioOutFormatReq *s = (SMsgAVIoctrlGetAudioOutFormatReq *)malloc(sizeof(SMsgAVIoctrlGetAudioOutFormatReq));
                s->channel = 0;
                [cam sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlGetAudioOutFormatReq)];
                free(s);
            }
        }
    }
    
#endif
    NSLog(@"CameraListForLiveViewController isRecvAudioFormat:%d", isRecvAudioFormat);
    
    
    return isRecvAudioFormat;
}



- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
}

#pragma mark 在滑动手势删除某一行的时候，显示出更多的按钮
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    // 添加一个删除按钮
    DTDevice *info = self.array[indexPath.row];

    __weak typeof(self) weakself = self;
    UITableViewRowAction *moreRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"重命名" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"更改用户名");
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"重命名" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        
        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
            textField.placeholder = @"请输入设备名";
        }];
        __weak typeof(alertController) alere = alertController;
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        __weak typeof(self) weakself = self;
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            if (![NSString isContainsTwoEmoji:alere.textFields.firstObject.text]&&[alere.textFields.firstObject.text length]<=8){
                if ([alere.textFields.firstObject.text length]<=0){
                    
                    return [SVProgressHUD showErrorWithStatus:@"设备名称不能为空"];
                }
                NSString *deviceName = alere.textFields.firstObject.text;
                
                [[DTCloudManager defaultJNI_iOS_SDK] renameDeviceByUUID:info.deviceUUID andDeviceName:alere.textFields.firstObject.text successCallback:^(NSDictionary *dic) {
                    
                    if ([dic[@"errcode"] integerValue] == 0) {
                        
                        info.deviceName = deviceName;
                        [weakself.tableView reloadData];
                        
                    }else{
                        
                        [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
                        
                    }

                } errorCallback:^(NSDictionary *dic) {
                    [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];

                }];
                
                

            }else{
                
                [SVProgressHUD showErrorWithStatus:@"输入名称过长或输入了非法字符"];
                
            }
            
        }];
        
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
        
    }];
    
    
    UITableViewRowAction *deletRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        [[DTCloudManager defaultJNI_iOS_SDK] unBindDeviceByUUID:info.deviceUUID successCallback:^(NSDictionary *dic) {
            
            [weakself.array removeObject:info];
            [weakself.tableView reloadData];
            
        } errorCallback:^(NSDictionary *dic) {
            
            [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
        }];
        
    }];
    
    moreRowAction.backgroundColor  = [UIColor colorWithHexString:@"646464"];
    deletRowAction.backgroundColor = [UIColor colorWithHexString:@"f8533d"];

    return @[deletRowAction,moreRowAction];
}

#pragma mark - --------------------------懒加载--------------------------
- (UITableView *)tableView{
    
    if (!_tableView) {
        
        __weak UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [superView addSubview:_tableView];
        //        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;//隐藏tableView的分割线
        //        _tableView.scrollEnabled = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        
    }
    return _tableView;
}

- (NSMutableArray *)array{
    
    if (!_array) {
        _array = [NSMutableArray array];
    }
    return _array;
}

#pragma mark - --------------------------约束--------------------------
- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.edges.mas_equalTo(superView);
        
    }];
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
